package com.zq.springadmin.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zq.springadmin.util.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.io.PrintWriter;


/*
* 用户未登录时，返回json格式的错误信息
* */


@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        // 返回json格式的错误信息
        Result<String> responseData = new Result<>(401,"当前用户未登录",null);

        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(responseData));



    }
}
